<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <footer-button :buttons="formState.buttons" />
          <a-form
            ref="formRef"
            :model="formData.data"
            :rules="formRules"
            :labelCol="{ span: 9 }"
          >
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('channelManage.label.channelType')"
                  name="chnType"
                  v-bind="validateInfos.chnType"
                >
                  <a-select
                    ref="select"
                    v-model:value="formData.data.chnType"
                    style="width: 100%"
                  >
                    <a-select-option
                      v-for="(item, index) in dictLists.data[
                        dictEnum.CHANNEL_TYPE
                      ]"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('channelManage.label.channelName')"
                  v-bind="validateInfos.chnName"
                  name="chnName"
                >
                  <a-input
                    v-model:value="formData.data.chnName"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="50"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.channelLeader')" name="chnHead">
                  <a-input
                    v-model:value="formData.data.chnHead"
                    :placeholder="t('placeholder.pleaseSelect')"
                    readonly
                  >
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('channelVisible')"
                      >
                        {{ t('button.select') }}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.channelSaleHead')" name="saleHead">
                  <a-input
                    v-model:value="formData.data.saleHead"
                    :placeholder="t('placeholder.pleaseSelect')"
                    readonly
                  >
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('channelVisible', 'sale')"
                      >
                        {{ t('button.select') }}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.bindStudents')" name="chnStudent">
                  <a-input
                    v-model:value="formData.data.chnStudent"
                    :placeholder="t('placeholder.pleaseSelect')"
                    readonly
                  >
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('studentVisible')"
                      >
                        {{ t('button.select') }}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.telephone')" ref="phone" name="phone">
                  <a-input-group compact :placeholder="t('placeholder.pleaseSelect')">
                    <a-select
                      style="width: 30%"
                      v-model:value="formData.data.zoneCode"
                    >
                      <a-select-option
                        v-for="(item, index) in dictLists.data[
                          dictEnum.ZONE_CODE
                        ]"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                    <a-input
                      style="width: 70%"
                      v-model:value="formData.data.phone"
                      :placeholder="t('channelManage.label.defaultCoChannelAppletAccount')"
                      :maxlength="11"
                    />
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="Email" ref="email" name="email">
                  <a-input
                    v-model:value="formData.data.email"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="25"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('channelManage.label.documentType')"
                  v-bind="validateInfos.papersType"
                >
                  <a-select
                    style="width: 100%"
                    :placeholder="t('placeholder.pleaseSelect')"
                    v-model:value="formData.data.papersType"
                    @change="handlePapers"
                  >
                    <a-select-option
                      v-for="item in dictLists.data[dictEnum.DOCUMENT_TYPE]"
                      :value="item.value"
                      :key="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('channelManage.label.certificateNo')"
                  ref="papersNum"
                  name="papersNum"
                >
                  <a-input
                    v-model:value="formData.data.papersNum"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="25"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.payAccountNumber')" name="payAmt">
                  <a-input
                    v-model:value="formData.data.payAmt"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="25"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.performanceCalculationPoint')" name="perfmNode">
                  <a-select
                    style="width: 100%"
                    :placeholder="t('placeholder.pleaseSelect')"
                    v-model:value="formData.data.perfmNode"
                  >
                    <a-select-option
                      v-for="(item) in dictLists.data[
                        dictEnum.CALCULATION_POINT
                      ]"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.cooperationStartTime')" name="beginTime">
                  <a-date-picker
                    style="width: 100%"
                    v-model:value="formData.data.beginTime"
                    :placeholder="t('placeholder.pleaseSelect')"
                    :maxlength="100"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.performanceForecast')" name="forecastNum">
                  <a-input
                    v-model:value="formData.data.forecastNum"
                    suffix="/元"
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="18"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.area')" name="belongsAdd">
                  <a-select
                    style="width: 100%"
                    :placeholder="t('placeholder.pleaseSelect')"
                    v-model:value="formData.data.belongsAdd"
                  >
                    <a-select-option
                      v-for="(item, index) in dictLists.data[dictEnum.IN_AREA]"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.responsibleSchool')" name="chargeSchool">
                  <a-input
                    v-model:value="formData.data.chargeSchool"
                    :placeholder="t('placeholder.pleaseSelect')"
                    readonly
                  >
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('universityVisible')"
                      >
                        {{ t('button.select') }}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.oppositePerson')" name="dockPeople">
                  <a-input
                    v-model:value="formData.data.dockPeople"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="50"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.organizationalNature')" name="organized">
                  <a-input
                    v-model:value="formData.data.organized"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="100"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.formOfCooperation')" name="tradeForms">
                  <a-input
                    v-model:value="formData.data.tradeForms"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="100"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item
                  :label="t('channelManage.label.channelProfile')"
                  :labelCol="{ span: 3 }"
                  name="remark"
                >
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="255"
                    v-model:value="formData.data.remark"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <div class="pre-title">{{ t('channelManage.label.commissionAllocation') }}</div>
        <a-card>
          <a-form
            :rules="modelRef"
            :model="modelForm.data"
            :labelCol="{ span: 9 }"
          >
            <a-row>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.calculationType')">
                  <a-select
                    style="width: 100%"
                    v-model:value="modelForm.data.commisType"
                    @change="handleRate"
                  >
                    <a-select-option
                      v-for="(item, index) in dictLists.data[
                        dictEnum.COMMIS_TYPE
                      ]"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col v-if="modelForm.data.commisType == 0" :span="8" :labelCol="{ span: 3 }">
                <a-form-item :label="t('channelManage.label.commissionPercentage')">
                  <a-input
                    v-model:value="modelForm.data.rate"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="18"
                    suffix="%"
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-button
                  v-if="modelForm.data.commisType == 1"
                  style="margin-left: 20px"
                  type="primary"
                  @click="handleCommis"
                >
                  {{ t('button.add') }}
                </a-button>
              </a-col>
            </a-row>
          </a-form>
          <a-row v-for="(item, index) in signaData.data" :key="index">
            <a-col :span="12">
              <a-form :model="item" style="width: 100%">
                <a-form-item :label="t('channelManage.label.numberOfSignatories')" :labelCol="{ span: 6 }">
                  <a-input
                    style="width: 45%"
                    v-model:value="item.min"
                    :placeholder="t('placeholder.pleaseEnter')"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                  -
                  <a-input
                    style="width: 45%"
                    v-model:value="item.max"
                    :placeholder="t('placeholder.pleaseEnter')"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-form>
            </a-col>
            <a-col :span="8">
              <a-form :model="item" style="width: 100%">
                <a-form-item :label="t('channelManage.label.numberOfSignatories')">
                  <a-input
                    v-model:value="item.rate"
                    :placeholder="t('placeholder.pleaseEnter')"
                    suffix="%"
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    allowClear
                    :maxlength="18"
                  />
                </a-form-item>
              </a-form>
            </a-col>
            <a-col :span="3">
              <a-button
                @click="handleDelCommis(index)"
                style="margin-left: 20px"
                type="danger"
              >
                {{ t('button.delete') }}
              </a-button>
            </a-col>
          </a-row>
        </a-card>
        <div class="pre-title">{{ t('channelManage.label.basicSalary') }}</div>
        <a-card>
          <a-form
            :rules="rulesRef"
            :model="rulesForm.data"
            :labelCol="{ span: 9 }"
          >
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title" style="padding-bottom: 30px">
                  {{ t('channelManage.label.campusAmbassadorBasicRewardAllocation') }}
                </div>
              </a-col>
              <a-col :span="8"></a-col>
              <a-col :span="8"></a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title">{{ t('channelManage.label.jianqunlaPeople') }}</div>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.probationReward')">
                  <a-input
                    v-model:value="rulesForm.data.bgppTrial"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个群"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.rewardAfterBecomingRegular')">
                  <a-input
                    v-model:value="rulesForm.data.bgppPositive"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个群"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title">{{ t('channelManage.label.collectAllKindsOfStudentResources') }}</div>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.probationReward')">
                  <a-input
                    v-model:value="rulesForm.data.collectTrial"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个群"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.rewardAfterBecomingRegular')">
                  <a-input
                    v-model:value="rulesForm.data.collectPositive"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个群"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title">{{ t('channelManage.label.seekLocalSponsorshipCooperation') }}</div>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.probationReward')">
                  <a-input
                    v-model:value="rulesForm.data.sponsorTrial"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.rewardAfterBecomingRegular')">
                  <a-input
                    v-model:value="rulesForm.data.sponsorPositive"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title">{{ t('channelManage.label.offlineActivityDisplay') }}</div>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.probationReward')">
                  <a-input
                    v-model:value="rulesForm.data.pshowTrial"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.rewardAfterBecomingRegular')">
                  <a-input
                    v-model:value="rulesForm.data.pshowPositive"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/个"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title">{{ t('channelManage.label.eventPlanning') }}</div>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.probationReward')">
                  <a-input
                    v-model:value="rulesForm.data.planTrial"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/场"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.rewardAfterBecomingRegular')">
                  <a-input
                    v-model:value="rulesForm.data.planPositive"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/场"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="4">
                <div class="title">{{ t('channelManage.label.monthlyPromotion') }}</div>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.probationReward')">
                  <a-input
                    v-model:value="rulesForm.data.promoteTrial"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/场"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('channelManage.label.rewardAfterBecomingRegular')">
                  <a-input
                    v-model:value="rulesForm.data.promotePositive"
                    :placeholder="t('channelManage.label.pleaseEnterAmount')"
                    suffix="元/场"
                    allowClear
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <div class="pre-title">{{ t('channelManage.label.attachmentInformation') }}</div>
        <a-card>
          <a-form ref="fileRef" :model="fileData.data" :rules="fileRules">
            <a-row>
              <a-col :span="24">
                <a-form-item
                  :label="t('channelManage.label.agreement')"
                  v-bind="validateInfosFile.protocalUrl"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 10 }"
                >
                  <a-input
                    v-show="false"
                    v-model:value="fileData.data.protocalUrl"
                  ></a-input>
                  <a-upload
                    name="file"
                    :file-list="fileProList"
                    :customRequest="handleUpload"
                    @change="handleProtocalChange"
                  >
                    <a-button> <a-icon type="upload" />{{ t('button.upload') }}</a-button>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item
                  :label="t('channelManage.label.otherAccessories')"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 10 }"
                >
                  <a-upload
                    name="files"
                    :file-list="fileList"
                    :customRequest="handleUpload"
                    @change="handleUploadChange"
                  >
                    <a-button> <a-icon type="upload" />{{ t('button.upload') }}</a-button>
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
    <student
      :visible="formState.studentVisible"
      @studentVisible="selectUniversity"
      @close="closeDialog"
    />
    <school
      :visible="formState.universityVisible"
      @selectUniversity="selectUniversity"
      @close="closeDialog"
    />
    <channel
      :visible="formState.channelVisible"
      @selectUniversity="selectUniversity"
      @close="closeDialog"
    />
    <userTree
      :visible="formState.visibleUserTree"
      @close="closeGive"
      :record="formState.recordGive"
    ></userTree>
  </page-layout>
</template>

<script>
import school from "./modal/school.vue";
import student from "./modal/student.vue";
import channel from "./modal/channel.vue";
import userTree from "./modal/user-tree";
import dictEnum from "@/const/dict";

import { Form, message } from "ant-design-vue";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import moment from "moment";

import {
  defineComponent,
  onActivated,
  reactive,
  onMounted,
  ref,
  toRaw,
} from "vue";
import { useRouter, useRoute } from "vue-router";

import { save, upload, details, update } from "@/api/module/channel-manage";
import { useI18n } from "vue-i18n";
const useForm = Form.useForm;
import { 
  emailPattern, // 邮箱
  passportPattern, // 护照
  businessPattern, // 营业执照
  idCardPattern, // 身份证号
  phoneCardPattern, // 电话号码
} from "@/utils/validator.js"

export default defineComponent({
  name: "channel-manage-add",
  components: {
    student,
    userTree,
    channel,
    school,
  },
  setup() {
    const { t } = useI18n();
    const formRef = ref(null);
    const fileRef = ref(null);
    const modelRef = ref(null);
    const rulesRef = ref(null);
    const fileProList = ref([]);
    const fileList = ref([]);

    const router = useRouter();
    const route = useRoute();
    let formData = reactive({
      data: {
        chnName: "",
        papersType: "",
        papersNum: "",
        zoneCode: '+86',
        phone: '',
        email: ''
      },
    });
    let modelForm = reactive({
      data: {
        commisType: '0',
      },
    });
    let rulesForm = reactive({
      data: {},
    });
    let fileData = reactive({
      data: {
        protocalUrl: "",
      },
    });
    const formRules = {
      chnName: [
        { required: true, message: "请输入渠道名称", trigger: "change" },
      ],
      phone: [
        { required: false, validator: async (rules, value) => {
          console.log('value: phone', value);
          // value = formData.data.phone
          if (!value) return Promise.resolve()
          if (!phoneCardPattern.test(value)) {
            return Promise.reject('请输入正确电话号码')
          } else {
            return Promise.resolve()
          }
        }, trigger: 'change' },
      ],
      email: [
        { required: false, validator: async (rules, value) => {
          if (!value) return Promise.resolve()
          if (!emailPattern.test(value)) {
            return Promise.reject('请输入正确的邮箱地址')
          } else {
            return Promise.resolve()
          }
        }, trigger: 'blur' },
      ],
      papersNum: [{ required: false, validator: (rules, value) => {
        if (!value) return Promise.resolve()
        const num = formData.data.papersType
        if (!Number(num)) return Promise.reject('请先选择证件类型')
        let result = false;
        switch (Number(num)) {
          case 1: 
            result = idCardPattern.test(value)
            break;
          case 2:
            result = passportPattern.test(value)
            break;
          case 3:
            result = businessPattern.test(value)
            break;
        }
        if (result) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入正确的证件号码')
        }
      }, trigger: 'blur' }],
    };
    const fileRules = {
      protocalUrl: [
        { required: false, message: "请选择上传协议", trigger: "blur" },
      ],
    };
    const { resetFields, validate, validateInfos } = useForm(
      formData.data,
      formRules
    );
    const resetFieldsFile = useForm(fileData.data, fileRules).resetFields;
    const validateFile = useForm(fileData.data, fileRules).validate;
    const validateInfosFile = useForm(fileData.data, fileRules).validateInfos;
    const signaData = reactive({
      data: [],
    });
    let dictLists = reactive({
      data: {
        chnType: "",
      },
    });

    const closeGive = function () {
      formState.visibleUserTree = false;
    };

    // 获取详情
    const getDetails = (id) => {
      if (!id) return;
      return details({ id }).then((res) => {
        if (res.success) {
          res.data.beginTime = res.data.beginTime
            ? moment(res.data.beginTime).format("YYYY-MM-DD")
            : "";
          const arr = JSON.parse(res.data.commisInfo);
          const phones = res.data.phone?res.data.phone.split('-'):[]
          const _zoneCode = phones.length ? phones[0] : ''
          const _phone = phones.length ? phones[1] : ''
          res.data.commisType == 1 && signaData.data.push(...arr);
          fileData.data = reactive({
            ...fileData.data,
            protocalUrl: res.data.protocalUrl,
            accessoryUrl: res.data.accessoryUrl,
          });
          fileProList.value = res.data.protocalUrl
            ? [{ url: res.data.protocalUrl || "", name: 'AAAAAA' }]
            : null;
          fileList.value = res.data.accessoryUrl
            ? [{ url: res.data.accessoryUrl || "", name: 'BBBBB' }]
            : null;
          formData.data = reactive({
            ...formData.data,
            ...res.data,
            phone: _phone,
            zoneCode: _zoneCode
          });
          modelForm.data = reactive({
            ...modelForm.data,
            ...res.data,
            rate: res.data.commisType == 0 && arr && arr.length ? arr[0].rate : ''
          });
          rulesForm.data = reactive({
            ...rulesForm.data,
            ...res.data,
          });
        }
      });
    };

    const resetForm = () => {
      formData.data = {
        chnName: "",
        papersType: "",
        papersNum: "",
        zoneCode: '+86'
      }
      modelForm.data = {
        commisType: '0',
      }
      rulesForm.data = {}
      fileData.data = {
        protocalUrl: "",
      }
      formRef.value.resetFields();
      // modelRef.value.resetFields();
      // fileRef.value.resetFields();
      // rulesRef.value.resetFields();
      signaData.data = [];
    };
    const handleSave = () => {
      formRef.value.validate().then(() => {
        fileRef.value.validate().then(() => {
          const _formData = toRaw(formData.data);
          const _modelForm = toRaw(modelForm.data);
          const _rulesForm = toRaw(rulesForm.data);
          const _fileData = toRaw(fileData.data);
          let result = {
            ..._formData,
            ..._modelForm,
            ..._rulesForm,
            ..._fileData,
          };
          if (result.commisType == 0) {
            signaData.data.push({min: 0, max: 0, rate: result.rate})
          }
          result.phone = result.zoneCode + '-' + result.phone
          result.commisInfo = JSON.stringify(signaData.data);
          if (result.id) {
            update(result)
              .then((res) => {
                if (res.success) {
                  message
                    .success({ content: "保存成功", duration: 1 })
                    .then(() => {
                      router.push({
                        path: "/market/channel-manage",
                      });
                      resetForm();
                    });
                } else {
                  message.warning({ content: "保存失败", duration: 1 });
                }
              })
              .catch((err) => {
                console.log("err: ", err);
                message.warning({ content: "保存失败", duration: 1 });
              });
          } else {
            save(result)
              .then((res) => {
                if (res.success) {
                  message
                    .success({ content: "保存成功", duration: 1 })
                    .then(() => {
                      router.push({
                        path: "/market/channel-manage",
                      });
                      resetForm();
                    });
                } else {
                  message.warning({ content: "保存失败", duration: 1 });
                }
              })
              .catch((err) => {
                message.warning({ content: "保存失败", duration: 1 });
              });
          }
        });
      });
    };
    const handleReset = () => {
      resetForm();
    };
    const formState = reactive({
      universityVisible: false,
      studentVisible: false,
      channelVisible: false,
      visibleUserTree: false,
      valueType: null,
      recordGive: {},
      buttons: [
        {
          name: "save",
          event: () => handleSave(),
          type: "primary",
          code: "",
        },
        {
          name: "reset",
          event: () => handleReset(),
          code: "",
        },
      ]
    });
    const labelCol = { span: 3, offset: 12 };
    const wrapperCol = { span: 14 };

    const openDialog = (value, type = null) => {
      formState.valueType = null;
      if (type) {
        formState.valueType = type
      }
      formState[value] = true;
    };

    const closeDialog = (type) => {
      formState[type] = false;
    };
    // 选择 负责人、学生、学校
    const selectUniversity = (data) => {
      formState[data.visible] = false;
      if (data.visible == "channelVisible") {
        if (formState.valueType == 'sale') {
          formData.data.saleHead = data.data.nickname;
          formData.data.saleHeadCode = data.data.id;
        } else {
          formData.data.chnHead = data.data.nickname;
          formData.data.chnHeadCode = data.data.id;
        }
      } else if (data.visible == "studentVisible") {
        formData.data.chnStudent = data.data.stuName;
      } else {
        formData.data.chargeSchool = data.data.schoolEnName;
      }
    };
    // 上传文件
    const handleUpload = (data) => {
      const formData = new FormData();
      formData.append("file", data.file);
      upload(formData).then((res) => {
        if (res.code === 500) {
          message.error({ content: "上传附件失败" });
          data.onError();
        } else {
          data.onSuccess(res.data);
        }
      });
    };
    // 附件
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      resFileList = resFileList.map((file) => {
        if (file.response) {
          file.url = file.response.path;
          fileData.data.accessoryUrl = file.response.path;
          fileData.data.accessoryName = file.response.name.replace('.', '');
        }
        return file;
      });
      fileList.value = resFileList;
    };
    // 协议
    const handleProtocalChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      resFileList = resFileList.map((file) => {
        if (file.response) {
          file.url = file.response.path;
          fileData.data.protocalUrl = file.response.path;
          fileData.data.protocalName = file.response.name.replace('.', '');
        }
        return file;
      });
      fileProList.value = resFileList;
    };
    // 添加阶梯配置
    const handleCommis = () => {
      signaData.data.push({
        min: null,
        max: null,
        rate: null,
      });
    };
    // 删除阶梯配置信息
    const handleDelCommis = (i) => {
      signaData.data = signaData.data.filter((item, index) => {
        if (index == i) {
          return false;
        }
        return true;
      });
    };

    const handlePapers = (value) => {
      formData.data.papersType = value;
    };

    const handleRate = (value) => {
      if (value == 0) {
        signaData.data = [];
      } else {
        formData.data.rate = '';
      }
    }
    onActivated(() => {
      const result = route.query;
      if (result && result.id) {
        getDetails(result.id);
      } else {
        resetForm()
      }
    });
    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.CHANNEL_TYPE,
        dictEnum.DOCUMENT_TYPE,
        dictEnum.CALCULATION_POINT,
        dictEnum.IN_AREA,
        dictEnum.COMMIS_TYPE,
        dictEnum.ZONE_CODE,
      ]);
    });
    return {
      t,
      formData,
      modelForm,
      rulesForm,
      formRef,
      modelRef,
      rulesRef,
      fileRef,
      fileRules,
      formRules,
      labelCol,
      wrapperCol,
      openDialog,
      formState,
      handleUploadChange,
      handleProtocalChange,
      selectUniversity,
      handleSave,
      closeDialog,
      closeGive,
      handlePapers,
      dictEnum,
      dictLists,
      resetFields,
      validateInfos,
      resetFieldsFile,
      validateInfosFile,
      signaData,
      handleUpload,
      fileList,
      fileProList,
      handleCommis,
      fileData,
      handleDelCommis,
      handleReset,
      handleRate,
    };
  },
});
</script>

<style lang="less" scoped>
.page-head {
  /deep/ .ant-page-header-heading-title {
    color: #2d8cf0;
  }
}

.pre-title {
  padding: 10px 25px;
  background-color: #f5f5f5;
  color: #555;
}

.price-title {
  padding: 10px 0;
}

.title {
  width: 100%;
  text-align: right;
  // padding-right: 20px;
}

.content-box {
  position: relative;
  width: 100%;
  min-height: 50px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  background-image: none;
  border-radius: 2px;
  padding: 10px 40px 10px 10px;

  .selects {
    position: absolute;
    color: #2d8cf0;
    right: 5px;
    cursor: pointer;
    top: 50%;
    transform: translateY(-50%);
  }
}

.form-label {
  /deep/ .ant-form-item-label > label::after {
    content: "" !important;
  }
}

/deep/ .ant-row {
  row-gap: 0 !important;
}
</style>